#-*- coding:utf-8 -*-
import direct.directbase.DirectStart 
#为了事件
from direct.showbase import DirectObject 
#为了碰撞
from pandac.PandaModules import * 


class Picker(DirectObject.DirectObject): 
    def __init__(self): 
        #建立碰撞材料
        self.picker= CollisionTraverser() 
        self.queue=CollisionHandlerQueue() 
        self.pickerNode=CollisionNode('mouseRay') 
        self.pickerNP=camera.attachNewNode(self.pickerNode) 
        self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask()) 
        self.pickerRay=CollisionRay() 
        self.pickerNode.addSolid(self.pickerRay) 
        self.picker.addCollider(self.pickerNP, self.queue) 
    
    
        #保存被选取的物体
        self.pickedObj=None 
        self.accept('mouse1', self.printMe) 

    #该函数为物体设置一个标志，让它可以拾取
    def makePickable(self,newObj): 
        newObj.setTag('pickable','true') 

    #该函数查找碰到射线且离摄影机最近的物体
    def getObjectHit(self, mpos): #mpos为鼠标的屏幕位置
        self.pickedObj=None #记得先清零
        #自动根据二维坐标建立射线  使射线从摄影机发出，指向鼠标的屏幕坐标
        self.pickerRay.setFromLens(base.camNode, mpos.getX(),mpos.getY()) 
        self.picker.traverse(render) 
        if self.queue.getNumEntries() > 0: 
            self.queue.sortEntries() 
            self.pickedObj=self.queue.getEntry(0).getIntoNodePath() 
            parent=self.pickedObj.getParent() 
            self.pickedObj=None 
        
        while parent != render: 
            if parent.getTag('pickable')=='true': 
                self.pickedObj=parent 
                return parent 
            else: 
                parent=parent.getParent() 
        return None 

    def getPickedObj(self): 
        return self.pickedObj 
    
    def printMe(self): 
        self.getObjectHit( base.mouseWatcherNode.getMouse()) 
        print self.pickedObj 

mousePicker=Picker() 

#载入这些模型
panda=loader.loadModel('panda') 
teapot=loader.loadModel('teapot') 
box=loader.loadModel('box') 

#把模型放到场景里
panda.reparentTo(render) 
panda.setPos(camera, 0, 100,0) 

teapot.reparentTo(render) 
teapot.setPos(panda, -30, 0, 0) 

box.reparentTo(render) 
box.setPos(panda, 30,0,0) 

mousePicker.makePickable(panda) 
mousePicker.makePickable(teapot) 
mousePicker.makePickable(box) 

run() 